#include "historypage.h"
#include "ui_historypage.h"
#include "usermgr.h"
#include <qpainter.h>

HistoryPage::HistoryPage(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::HistoryPage)
{
    ui->setupUi(this);
    connect(ui->historyTable, &HistoryTable::refreshData, this, &HistoryPage::pullData);
}

HistoryPage::~HistoryPage()
{
    delete ui;
}

void HistoryPage::setSeacher(SearchEngine<Page::PAGE_HISTORY> *searcher)
{
    m_searcherPtr = searcher;
}

void HistoryPage::paintEvent(QPaintEvent *event)
{
    QPainter painter(this);
    painter.fillRect(rect(),  QColor(248, 250, 255)); // RGB颜色
    // 可选：调用基类绘制其他内容（如边框）
    QWidget::paintEvent(event);
}

void HistoryPage::on_BackUpBtn_clicked()
{
    ui->historyTable->uploadAllSelected();
}

void HistoryPage::on_SelectAll_clicked()
{
    bool hasSelectedItems = !ui->historyTable->getSelectedRecords().isEmpty();

    if(hasSelectedItems) {
        // 如果已有选中项，则取消全选
        ui->SelectAll->setChecked(false);
        ui->historyTable->deselectAll();
    } else {
        // 如果没有选中项，则全选
        ui->historyTable->selectAll();
    }
}

void HistoryPage::on_DeleteAllSelectedBtn_clicked()
{
    auto selectedVec = ui->historyTable->getSelectedRecords();
    for(const auto selected : selectedVec){
        qDebug()<<selected->getFileInfo().fileId;
        m_dao.deleteByFileId(selected->getFileInfo().fileId);
    }
    ui->historyTable->deleteAllSelected();
}

void HistoryPage::scrollToItem(qint64 fileId)
{
    ui->historyTable->scrollToItem(fileId);
}

void HistoryPage::setMainWindow(MainWindow *mainWindow)
{
    m_mainWindow = mainWindow;

    connect(m_mainWindow, &MainWindow::refresh, this, &HistoryPage::pullData);
}

//后期改成从ResServer->sqlite: file_info表拉取50条记录
void HistoryPage::pullData()
{
    qDebug() << "正在拉取第" << m_currentPage << "页数据";

    QList<HistoryItemInfo> records = m_dao.findByUserId(
        UserMgr::GetInstance()->uid(),  // 使用实际用户ID
        m_pageSize,
        (m_currentPage - 1) * m_pageSize
        );

    if (records.isEmpty())  {
        qDebug() << "未查询到历史记录";
        return;
    }
    // 使用记录
    for (const HistoryItemInfo& record : records) {
        SearchMetaData<Page::PAGE_HISTORY> meta = record.toHistoryMetaData();
        m_searcherPtr->insertRecord(meta.fileName, meta.fileId, meta);
        ui->historyTable->appendRecord(record);
        //qDebug()<<record.fileId;
    }

    // 更新分页状态
    if (records.size()  < m_pageSize) {
        qDebug() << "最后一页数据，共" << records.size()  << "条";
    } else {
        m_currentPage++;  // 准备加载下一页
    }
}

